<!-- 组织详情左侧组件 -->
<template>
  <div class="role-list">
    <div @click="collapse" class="collapseBtn">
      <IconCaretRight v-if="isCollapsed" />
      <IconCaretLeft v-else />
    </div>
    <a-layout class="layout-demo">
      <a-layout-sider
        :resize-directions="['right']"
        collapsible
        breakpoint="xl"
        hide-trigger
        :collapsed="isCollapsed"
        :collapsed-width="0"
      >
        <div>
          <a-scrollbar style="height: 100%; overflow: auto">
            <div class="scroll">
              <a-input-search
                allow-clear
                class="search"
                placeholder="输入分类名称"
                v-model="searchVal"
              />

              <div class="scroll-content">
                <a-tree
                  :fieldNames="{
                    key: 'id',
                    title: 'C30BBF36A5AF541F7A2657671DEE2EDD6'
                  }"
                  :data="treeData"
                  v-model:expanded-keys="expandKey"
                  v-model:selected-keys="selectedKeys"
                  showLine
                  @select="selectTree"
                >
                  <template #switcher-icon="node, { isLeaf }">
                    <IconDown v-if="!isLeaf" />
                    <IconStar v-if="isLeaf" />
                  </template>
                  <template #title="nodeData">
                    <template
                      v-if="
                        ((index = getMatchIndex(
                          nodeData['C30BBF36A5AF541F7A2657671DEE2EDD6']
                        )),
                        index < 0)
                      "
                    >
                      <!-- <span
                        :style="{
                          paddingLeft:
                            nodeData.level > 2
                              ? '32px'
                              : (nodeData.level - 1) * 16 + 'px'
                        }"
                        >{{
                          nodeData['C30BBF36A5AF541F7A2657671DEE2EDD6']
                        }}</span
                      > -->
                      <span>{{
                        nodeData['C30BBF36A5AF541F7A2657671DEE2EDD6']
                      }}</span>
                    </template>
                    <span v-else>
                      {{
                        nodeData['C30BBF36A5AF541F7A2657671DEE2EDD6']?.substr(
                          0,
                          index
                        )
                      }}
                      <span style="color: var(--color-primary-light-4)">
                        {{
                          nodeData['C30BBF36A5AF541F7A2657671DEE2EDD6']?.substr(
                            index,
                            searchVal.length
                          )
                        }} </span
                      >{{
                        nodeData['C30BBF36A5AF541F7A2657671DEE2EDD6']?.substr(
                          index + searchVal.length
                        )
                      }}
                    </span>
                  </template>
                </a-tree>
              </div>
            </div>
          </a-scrollbar>
        </div>
      </a-layout-sider>
    </a-layout>
  </div>
</template>

<script lang="ts" setup>
import { flatTree, dataTreeFilter } from '@/utils/utils';
import {
  GetOrganizationList,
  PostOrganizationList
} from '@/apis/management/organization/organizationManagement';

const props = withDefaults(
  defineProps<{
    isPersonManagement: boolean; // 判断是否是人员管理左边的侧边栏
  }>(),
  {
    isPersonManagement: false
  }
);

const router = useRouter();
const route = useRoute();
let searchVal = ref(''); // 搜索框
let originTreeData: any = ref([]); // 储存最初的树形数据
let expandKey: any = ref([]); // 储存当前搜索要展开的选项
let selectedKeys = ref([]);

// 搜索值
const searchData = (keyword: string) => {
  const loop = (data: any) => {
    const result: any = [];
    data.forEach((item: any) => {
      if (
        item['C30BBF36A5AF541F7A2657671DEE2EDD6']
          .toLowerCase()
          .indexOf(keyword.toLowerCase()) > -1
      ) {
        result.push({ ...item });
      } else if (item.children) {
        const filterData = loop(item.children);
        if (filterData.length) {
          result.push({
            ...item,
            children: filterData
          });
          expandKey.value.push(item.id);
        }
      }
    });
    return result;
  };

  return loop(originTreeData.value);
};

/* 储存实时的属性数据 */
const treeData = computed(() => {
  if (!searchVal.value) return originTreeData.value;
  return searchData(searchVal.value);
});

let flatData = ref<any>([]); // 储存扁平化的数据
// 获取列表数据
const getTableData = async () => {
  try {
    const res = await GetOrganizationList({});
    originTreeData.value = dataTreeFilter(res);
    flatData.value = flatTree(originTreeData.value);
    // 默认展开3层
    flatData.value.forEach((item: any) => {
      if (item.level < 4) expandKey.value.push(item.id);
      if (item.id === +route.query.id || item.id === +route.params.id)
        selectedKeys.value.push(item.id);
    });
  } catch (error: unknown) {
    console.log(error);
  }
};
getTableData();

let isCollapsed = ref(false); // 判断是否收起
const collapse = (collapsed: boolean) => {
  isCollapsed.value = !isCollapsed.value;
};

// 获取符合的数据
const getMatchIndex = (name: string): number => {
  if (!searchVal.value) return -1;
  return name.toLowerCase().indexOf(searchVal.value.toLowerCase()) as number;
};

// 点击导航栏跳往对应详情
const selectTree = (selectedKeys: number, data: any) => {
  if (props.isPersonManagement) {
    router.push({
      name: 'OrganizationPersonManagement',
      params: {
        id: data.node.id,
        name: data.node.name
      }
    });
  } else {
    router.push({
      name: 'OrganizationDetail',
      query: {
        id: data.node.id,
        ownerType: data.node.useTemplate.ownerType
      }
    });
  }
};

let isClose = ref(false);
const close = () => {
  isClose.value = !isClose.value;
};
</script>

<style scoped lang="less">
.role-list {
  position: relative;
  padding: 15px;
  .collapseBtn {
    position: absolute;
    z-index: 999;
    top: 40%;
    right: 15px;
    height: 70px;
    width: 15px;
    background-color: #eee;
    line-height: 70px;
    text-align: center;
    cursor: pointer;
  }
  .layout-demo {
    height: 100%;
    :deep(.arco-layout-sider) {
      // min-width: 300px;
      max-width: 500px;
    }
  }
  .scroll {
    padding: 10px;
    overflow: hidden;
    .search {
      background-color: #fff;
      height: 40px;
      border: 1px solid #ccc;
    }
  }
}
// :deep(.arco-tree-node-indent) {
//   width: 0px;
//   height: 0px;
// }
</style>
